package hero_info

import (
	"go_server/game_server/protocol/pb"
	"go_server/game_server/util"
	"go_server/zinx/ziface"
	"go_server/zinx/zlog"
)

func (s *Hero_info_service) S2C_UnEquipCell(conn ziface.IConnection, roleid int64, msg *pb.UnEquipCellC2S) pb.ErrorCodeManager {
	hero := Hero_info_serviceObj.LoadByRoleId(roleid)
	unequipcells := make(map[int32][]int32)

	for hidx, hsid := range msg.Heroserids {
		if _, k1 := unequipcells[hsid]; k1 {
			unequipcells[hsid] = make([]int32, 0)
		}
		if len(msg.Cellserids) > hidx {
			unequipcells[hsid] = append(unequipcells[hsid], msg.Cellserids[hidx])
		}
	}

	rstHeros, rstRoleCells, ok, code := s.onUnEquipCell(hero, unequipcells)
	if ok {
		msgS2C := &pb.UpdateHeroCellS2C{
			Heros: rstHeros,
			Cells: rstRoleCells,
		}
		defer func() {
			if msgS2C != nil {
				zlog.Debugf("ProtocolManager_UpdateHeroCell %v", msgS2C)
				defer func() {
					conn.SendBuffPBMsg(uint32(pb.ProtocolManager_UpdateHeroCell), msgS2C)
				}()
			}
		}()
	}
	return code
}

func (s *Hero_info_service) onUnEquipCell(hero *Cache_hero_info, unequipcells map[int32][]int32) ([]*pb.HeroCardData, []*pb.HeroCellData, bool, pb.ErrorCodeManager) {
	updataheros := util.NewSet[int32]()      //有变更的英雄数据
	unequipherocells := util.NewSet[int32]() //英雄卸载的细胞数据

	rstCode := pb.ErrorCodeManager_HERO_INFO_ERROR_EQUIPCELL
	if hero != nil && unequipcells != nil && len(unequipcells) > 0 {
		for heroserid, cells := range unequipcells {
			if hv, h1 := hero.Heros[heroserid]; h1 {
				if cells != nil && len(cells) > 0 {
					for _, cellserid := range cells {
						delcidxs := util.NewSet[int]()

						for cidx, cv := range hv.Cells {
							if cv.Serid == cellserid {
								if rcv, r1 := hero.RoleCells[cv.Serid]; r1 { //如果有细胞数据，则加数量
									rcv.Count++
								} else { //如果没有，则添加新的
									hero.RoleCells[cv.Serid] = &Cache_hero_info_field_cell{
										Serid: cv.Serid,
										CfgId: cv.CfgId,
										Lv:    cv.Lv,
										Count: 1,
										Idx:   0,
									}
								}
								delcidxs.Add(cidx)
								unequipherocells.Add(cv.Serid)
								updataheros.Add(heroserid)

								rstCode = pb.ErrorCodeManager_SUCCESS
							}
						}

						for _, v := range delcidxs.Elements() {
							delete(hv.Cells, v)
						}
					}
				}
			}
		}
	}

	go hero.SaveDB_HeroInfo_Cells()
	rstHeros := make([]*pb.HeroCardData, 0)
	if updataheros != nil {
		for _, v := range updataheros.Elements() {
			rstHeros = append(rstHeros, hero.Heros[v].ToPB_HeroCardData())
		}
	}

	rstRoleCells := make([]*pb.HeroCellData, 0)
	if unequipherocells != nil {
		for _, v := range unequipherocells.Elements() {
			rstRoleCells = append(rstRoleCells, hero.RoleCells[v].To_PbData())
		}
	}

	return rstHeros, rstRoleCells, len(rstHeros) > 0 || len(rstRoleCells) > 0, rstCode
}
